﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SignApp
{
    using Microsoft.Win32;
    using SharpSoft;
    using SharpSoft.WPF;
    using System.Security.Cryptography;

    /// <summary>
    /// CryptPage.xaml 的交互逻辑
    /// </summary>
    public partial class CryptPage : Page
    {
        public CryptPage()
        {
            this.DataContext = this;
            InitializeComponent();


            var knames = Enum.GetValues(typeof(RsaKeyType));
            var dic = new Dictionary<RsaKeyType, string>();
            foreach (RsaKeyType item in knames)
            {
                dic.Add(item, Enum.GetName(typeof(RsaKeyType), item));
            }
            cmb_keyTypes.ItemsSource = dic;
            cmb_keyTypes.SelectedValuePath = "Key";
            cmb_keyTypes.DisplayMemberPath = "Value";
            cmb_keyTypes.SelectedIndex = 0;
        }

        public RsaKey Key
        {
            get { return (RsaKey)GetValue(KeyProperty); }
            set { SetValue(KeyProperty, value); }
        }

        public static readonly DependencyProperty KeyProperty =
            DependencyProperty.Register("Key", typeof(RsaKey), typeof(CryptPage), new PropertyMetadata(null));



        private async void btn_import_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "导入密钥";
            ofd.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            ofd.FileName = $"prikey.txt";
            ofd.CheckFileExists = true;
            ofd.CheckPathExists = true;
            var result = ofd.ShowDialog();
            if (result.GetValueOrDefault())
            {
                var file = ofd.FileName;
                var folder = System.IO.Path.GetDirectoryName(file);
                var prifile = System.IO.Path.Combine(folder, "prikey.txt");
                var pubfile = System.IO.Path.Combine(folder, "pubkey.txt");
                if (System.IO.File.Exists(prifile) && System.IO.File.Exists(pubfile))
                {
                    if (this.Key == null)
                    {
                        this.Key = new RsaKey(RsaKeyType.XML, 2048, false);
                    }
                    Encoding encoding = new UTF8Encoding(false);
                    this.Key.PrivateKey = System.IO.File.ReadAllText(prifile, encoding);
                    this.Key.PublicKey = System.IO.File.ReadAllText(pubfile, encoding);
                    CopyKey();
                }
                else
                {
                    dlgError("公钥/私钥文件不存在。");
                }
            }
        }

        public static void dlgError(string msg, string title = null)
        {
            MessageBox.Show(msg, title, MessageBoxButton.OK, MessageBoxImage.Error);

        }

        private void CopyKey()
        {
            if (cmb_keyTypes.SelectedValue is RsaKeyType)
            {

                var keytype = (RsaKeyType)cmb_keyTypes.SelectedValue;
                var keysize = (int)nud_keyLen.Value;
                var formatkey = cb_format.IsChecked.GetValueOrDefault();
                var key = new RsaKey(keytype, keysize, formatkey);
                if (this.Key != null)
                {
                    key.PrivateKey = this.Key.PrivateKey;
                    key.PublicKey = this.Key.PublicKey;
                }
                this.Key = key;
            }
        }

        private async void btn_de_Click(object sender, RoutedEventArgs e)
        {
            CopyKey();
            try
            {
                txt_de.Text = this.Key.Decrypt(txt_en.Text, RSAEncryptionPadding.OaepSHA1);
            }
            catch (Exception ex)
            {
                dlgError("解密失败。" + ex.Message);
            }

        }

        private async void btn_en_Click(object sender, RoutedEventArgs e)
        {
            CopyKey();
            try
            {
                txt_en.Text = this.Key.Encrypt(txt_de.Text, RSAEncryptionPadding.OaepSHA1);

            }
            catch (Exception ex)
            {

                dlgError("加密失败。" + ex.Message);
            }

        }

        private void btn_depub_Click(object sender, RoutedEventArgs e)
        {
            txt_de.Text = this.Key.DecryptByPub(txt_en.Text, RSAEncryptionPadding.Pkcs1);
        }

        private void btn_enpri_Click(object sender, RoutedEventArgs e)
        {
            txt_en.Text = this.Key.EncryptByPri(txt_de.Text, RSAEncryptionPadding.Pkcs1);
        }

        private void cmb_keyTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CopyKey();
        }

        private void nud_keyLen_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            CopyKey();
        }
    }
}
